package cn.com.connext.scrm.service;

import cn.com.connext.scrm.config.Constants;
import cn.com.connext.scrm.domain.master.*;
import cn.com.connext.scrm.repository.master.*;
import cn.com.connext.scrm.service.dto.*;
import cn.com.connext.scrm.service.mapper.OrderService;
import cn.com.connext.scrm.service.mapper.PrizeMapper;
import cn.com.connext.scrm.service.mapper.TmpMsgRecordService;
import cn.com.connext.scrm.utils.CouponUtils;
import cn.com.connext.scrm.utils.RandomUtils;
import cn.com.connext.scrm.web.rest.vm.*;
import com.alibaba.excel.util.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import com.wechat.pay.contrib.apache.httpclient.auth.AutoUpdateCertificatesVerifier;
import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Validator;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.PrivateKey;
import java.text.SimpleDateFormat;
import java.time.ZonedDateTime;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

/**
 * 2 * @Author: shawn
 * 3 * @Date: 2020/8/11 4:13 下午
 * 4
 */
@Service
@Transactional
public class PrizeService {
    private final Logger log = LoggerFactory.getLogger(PrizeService.class);
    ReentrantLock lock = new ReentrantLock();
    @Autowired
    private PrizeRepository prizeRepository;

    @Autowired
    private PrizeGoodService prizeGoodService;

    @Autowired
    private PrizeCodeRepository prizeCodeRepository;

    @Autowired
    private PrizeRateService prizeRateService;
    @Autowired
    private DwaGetCouponService dwaGetCouponService;

    @Autowired
    private PrizeExtRepository prizeExtRepository;
    @Autowired
    private TmpMsgRecordService tmpMsgRecordService;

    @Autowired
    private PrizeMapper prizeMapper;

    @Autowired
    private AccessTokenImpl accessTokenImpl;

    @Autowired
    private MemberService memberService;
    @Autowired
    private UploadCodeService uploadCodeService;

    @Autowired
    private TaskRecordRepository taskRecordRepository;

    @Autowired
    CodeUserService codeUserService;

    @Autowired
    MemberRepository memberRepository;

    @Autowired
    private QrCodeRepository qrCodeRepository;

    @Autowired
    private QrCodeScanRepository qrCodeScanRepository;

    @Autowired
    private DrawActivityRepository drawActivityRepository;

    @Autowired
    private DrawPrizeCountRepository drawPrizeCountRepository;

    @Autowired
    private MdmHelpMsgRepository mdmHelpMsgRepository;

    @Autowired
    private MdmHelpActivityRepository mdmHelpActivityRepository;

    @PersistenceContext
    private EntityManager entityManager;
    @Autowired
    private OrderService orderService;

    @Autowired
    private TaskRepository taskRepository;
    /**
     * 抽奖
     *
     * @param unionId
     * @param memberShipId
     * @return
     */
    public JsonResult prize(String unionId, String memberShipId, String activityId, Integer cutPoint,String openId,Integer type,Integer isReceive) {
        JsonResult result = new JsonResult();
        Prize prize = null;
        Integer goodId = null;
        JsonResult jsonResult = null;
        lock.lock();
        try {
            DrawActivity activity = drawActivityRepository.findOne(activityId);
            //类型为抽奖 活动包含未中奖
            if (StringUtils.equals(activity.getActivityType(), "1") && activity.getNotHavePrizeFlag() == 1) {
                List<PrizeGood> enableGoods = prizeGoodService.getEnableIdsByActivityId(activityId);
                if (enableGoods.size() == 0) {
                    result.setState(4);
                    result.setMessage("很遗憾您未抽中，谢谢参与");
                    result.setData(Constants.NOT_HAVE_PRIZE_IMG_URL);
                    return result;
                }
                //奖品库存
                Integer stock = 0;

                //未中奖概率
                Double nothavePrize = 0D;
                //中奖概率合计
                Double maxNum = 0D;
                for (PrizeGood good : enableGoods) {
                    maxNum = maxNum + good.getProbability();
                }
                if (maxNum == 0) {
                    result.setState(-1);
                    result.setMessage("概率出问题了");
                    return result;
                }
                log.info("最大数:{}", maxNum);
                nothavePrize = 100 - maxNum;
                maxNum = maxNum + nothavePrize;
                //设置未中奖属性  没有id标识为未中奖
                PrizeGood newPrizeGood = new PrizeGood();
                newPrizeGood.setProbability(nothavePrize);
                //将未中奖放置首位先计算未中奖
                List<PrizeGood> prizeGoods = new ArrayList<>();
                prizeGoods.add(newPrizeGood);
                prizeGoods.addAll(enableGoods);

                //获取0-总概率值得随机数
                Double min = 0d;
                Double randomNum = min + new Random().nextDouble() * (maxNum - min);
                log.info("randomNum:{}", randomNum);
                for (PrizeGood good : prizeGoods) {
                    randomNum = randomNum - good.getProbability();
                    if (randomNum <= 0) {
                        goodId = good.getId();
                        stock = good.getStock();
                        break;
                    }
                }

                log.info("奖品id:{}", goodId);
                log.info("奖品stock:{}", stock);
                //更新或新增抽奖次数记录
                this.saveOrUpdateDrawPrizeCount(activityId, unionId);
                //goodId为空和库存小于等于零表示未中奖
                if (goodId == null || stock <= 0) {
                    result.setState(4);
                    result.setMessage("很遗憾您未抽中，谢谢参与");
                    result.setData(Constants.NOT_HAVE_PRIZE_IMG_URL);
                    return result;
                }
            } else {
                List<PrizeGood> enableGoods = prizeGoodService.getEnableIdsAndStockIsNotNullByActivityId(activityId);
                if (enableGoods.size() == 0) {
                    result.setState(-1);
                    result.setMessage("很遗憾您未抽中，谢谢参与");
                    return result;
                }
                Double maxNum = 0d;
                for (PrizeGood good : enableGoods) {
                    maxNum = maxNum + good.getProbability();
                }
                if (maxNum == 0) {
                    result.setState(-1);
                    result.setMessage("概率出问题了");
                    return result;
                }
                log.info("最大数:{}", maxNum);
                //获取0-总概率值得随机数
                Double min = 0d;
                Double randomNum = min + new Random().nextDouble() * (maxNum - min);
                log.info("randomNum:{}", randomNum);
                for (PrizeGood good : enableGoods) {
                    randomNum = randomNum - good.getProbability();
                    if (randomNum <= 0) {
                        goodId = good.getId();
                        break;
                    }
                }
                log.info("奖品id:{}", goodId);
            }

            Boolean flag = cutStock(goodId, activityId);
            if (!flag) {
                result.setState(-1);
                result.setMessage("系统繁忙");
                return result;
            }
        } catch (Exception e) {
            log.error("e:{}", e);
        } finally {
            lock.unlock();
        }
        //通过奖品ID获取当前时间的奖品
        PrizeGood good = prizeGoodService.findById(goodId);
        //扣分
        cutPoint(memberShipId, cutPoint);
        log.info("扣分结束");

        /**
         * 210804 微信罗森卡券发放
         */
        //判断类型为卡券且为微信卡券,抽中微信卡券
        String bodyAsString = "";
        if(good.getType() == 3 ){
            if (good.getCouponType() == null || StringUtils.isEmpty(good.getCouponType()))
                if ("0".equals(good.getWxCouponsType())) {

                    try {
                    //序列号
                    String merchantSerialNumber = "32075FA334FA59896AEF7879670E82AB13075120";
                    //商户号
                    String merchantId = "1612505750";
                    String apiV3Key = "20210805A161000ADiageoOmata0417y";
                    //私钥
                    PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(
                        new FileInputStream(File.separator+"etc"+File.separator+"apiclient_key.pem"));
                    //不需要传入微信支付证书了 需要v3Key
                    AutoUpdateCertificatesVerifier verifier = new AutoUpdateCertificatesVerifier(
                        new WechatPay2Credentials(merchantId, new PrivateKeySigner(merchantSerialNumber, merchantPrivateKey)),
                        apiV3Key.getBytes("utf-8"));
                    WechatPayHttpClientBuilder builder = WechatPayHttpClientBuilder.create()
                        .withMerchant(merchantId, merchantSerialNumber, merchantPrivateKey)
                        .withValidator(new WechatPay2Validator(verifier));

                    HttpClient httpClient = builder.build();
                    StringBuffer posturi = new StringBuffer("https://api.mch.weixin.qq.com/v3/marketing/favor/users/");
                    posturi.append(openId).append("/coupons");
                    String uri = posturi.toString();
                    HttpPost httpPost = new HttpPost(uri);
                    httpPost.addHeader("Accept", "application/json");
                    httpPost.addHeader("Content-type","application/json; charset=utf-8");
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    ObjectMapper objectMapper = new ObjectMapper();

                    ObjectNode rootNode = objectMapper.createObjectNode();
                    String outRequestNo = merchantId + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + RandomUtils.getRandomString2(7);
                    rootNode.put("stock_id",good.getStockId());
                    rootNode.put("out_request_no",outRequestNo);
                    rootNode.put("appid", Constants.APPID);
                    rootNode.put("stock_creator_mchid",good.getStockCreatorMchid());
                    objectMapper.writeValue(bos, rootNode);
                    httpPost.setEntity(new StringEntity(bos.toString("UTF-8"), "UTF-8"));
                    CloseableHttpResponse response = (CloseableHttpResponse) httpClient.execute(httpPost);

                    //此处格式转换如果不是正确的json格式则会抛出异常
                    bodyAsString = EntityUtils.toString(response.getEntity());
                    log.info("原始微信接口返回内容"+bodyAsString);
                    JSONObject s = JSONObject.parseObject(bodyAsString);
                    String coupon_id = s.getString("coupon_id");
                    bodyAsString = coupon_id;
                    log.info("解析后内容为："+bodyAsString);
                    if (StringUtils.isBlank(bodyAsString)) {
                        result.setState(-1);
                        result.setMessage("参与次数已达上限");
                        return result;
                    }
                } catch (IOException e) {
                    e.getStackTrace();
                }
            }
        }

        prize = new Prize();
        prize.setUnionId(unionId);
        //奖品ID
        prize.setGoodId(goodId);
        prize.setCreateTime(new Date());
        prize.setUpdateTime(new Date());
        prize.setAddPoint(false);
        if (StringUtils.isNotEmpty(activityId)) {
            prize.setActivityId(activityId);
        }
        //210804新增微信卡券
        if (StringUtils.isNotEmpty(good.getStockId())) {
            prize.setStockId(good.getStockId());
        }
        if (StringUtils.isNotEmpty(bodyAsString)) {
            prize.setCouponId(bodyAsString);
        }
        prize.setVerifyStatus("0");

        Prize prize1 = prizeRepository.saveAndFlush(prize);
        PrizeDTO dto = prizeMapper.toDto(prize);
        //如果抽中卡券包-------------------20201112添加
        if(good.getType() ==4){
            log.info("抽中卡券:{}",good.getId());
            PrizeCode code =uploadCodeService.findRandomCodeNoUse(good.getId());
            if(code !=null){
                dto.setCouponCode(code.getCode());
                code.setIsUse(2);
                code.setUseDate(new Date());
                code.setUnionId(unionId);
                code.setPrizeId(prize1.getId());
                uploadCodeService.edit(code);
            }
        }
        if (StringUtils.isNotEmpty(good.getGoodName())) {
            dto.setGoodName(good.getGoodName());
        }
        dto.setType(good.getType());
        //增加奖品图片
        if (StringUtils.isNotEmpty(good.getGoodImg())) {
            dto.setGoodImg(good.getGoodImg());
        }
        if (StringUtils.isNotEmpty(good.getPagePath())) {
            dto.setPagePath(good.getPagePath());
        }
        if (null != good.getPoint()) {
            dto.setPoint(good.getPoint());
        }
        if (StringUtils.isNotEmpty(good.getCardId())) {
            dto.setCardId(good.getCardId());
        }
        if (StringUtils.isNotEmpty(good.getCode())) {
            dto.setCode(good.getCode());
        }
        if (StringUtils.isNotEmpty(good.getCouponType())) {
            dto.setCouponType(good.getCouponType());
        }
        dto.setMgmUrl(good.getMgmUrl());
        dto.setMgmButtonName(good.getMgmButtonName());
        dto.setMgmStatus(good.getMgmStatus());
        dto.setQrCodeId(good.getQrCodeId());
        dto.setHxContent1(good.getHxContent1());
        dto.setHxContent2(good.getHxContent2());
        log.info("dto:{}", dto.toString());
        if (good.getType() == 0) {
            if (good.getPoint() == null || good.getPoint() == 0) {
                good.setPoint(50);
            }
        }
        final Integer prizeId = prize.getId();
        //第一次抽奖赠送10积分
        List<TaskRecord> list = taskRecordRepository.findByUserIdAndTaskType(unionId,11);
        if(list == null || list.size() ==0){
            // 增加：2021-12-20 原因：增加unionid的真伪判断
            //根据membershipId 查询member表 获取会员用户
            Member member = memberRepository.getMembershipId(memberShipId);
            if (null == member){
                log.info("没有获取到会员信息 req: {}",JSON.toJSONString(memberShipId));
                jsonResult.setState(1);
                jsonResult.setMessage("没有获取到会员信息");
                return jsonResult;
            }
            Task task =taskRepository.findOne("11");
            // 用会员用户的union_id + task.getType() 这两个字段查询
            List<TaskRecord> taskRecordList = taskRecordRepository.findByUserIdAndTaskType(member.getUnionId(), task.getType());
            //验证返回数据大于等于1
            if (taskRecordList.size() >= 1) {
                log.info("非法操作 req: {}",JSON.toJSONString(memberShipId));
                jsonResult.setState(1);
                jsonResult.setMessage(task.getType().compareTo(11) == 0 ? "参与活动超过一次无法获取积分" : "参与活动超过一次无法获取积分");
                return jsonResult;
            }

            // end-------2021-12-20
            String accessToken = accessTokenImpl.getAccessToken();
            String requestUrl = Constants.PointIncr.replace("MEMBERSHIP", memberShipId).replace("ACCESSTOKEN", accessToken);
            TaskRecord taskRecord = new TaskRecord();
            taskRecord.setCreateTime(new Date());
            taskRecord.setTaskType(11);
            taskRecord.setUserId(unionId);
            taskRecordRepository.save(taskRecord);
            log.info("本地第一次抽奖添加积分完成");
            ExecutorService service = Executors.newSingleThreadExecutor();
            service.execute(() -> {
                Date currentTime = new Date();
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(currentTime);
                calendar.add(Calendar.HOUR, -8);
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
                String timeStamp = formatter.format(calendar.getTime());
                PointDTO dto2 = new PointDTO();
                dto2.setContentName("第一次抽奖赠送积分");
                dto2.setSource("帝亚吉欧会员俱乐部");
                dto2.setDate(timeStamp);
                dto2.setPattern(4);//第一次积分兑礼
                dto2.setPoint(10);
                OkHttpClient client = new OkHttpClient().newBuilder()
                    .build();
                MediaType mediaType = MediaType.parse("application/json");
                RequestBody body2 = RequestBody.create(mediaType, JSON.toJSONString(dto2));
                Request request2 = new Request.Builder()
                    .url(requestUrl)
                    .method("POST", body2)
                    .addHeader("Content-Type", "application/json")
                    .build();
                try {
                    Response response2 = client.newCall(request2).execute();
                    String jsresult = new String(response2.body().bytes());
                    log.info("第一次抽奖赠送积分,返回值:{}", jsresult);
                    response2.body().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        }
        if (good.getType() == 0) {
            ExecutorService service = Executors.newSingleThreadExecutor();
            service.execute(() -> {
                addPoint(memberShipId, good.getPoint(), prizeId,unionId);
                log.info("加分结束");
            });
        }

        dto.setButtonText(good.getButtonText());

        if (good.getRemark()!=null){
            dto.setRemark(good.getRemark());
        }

        if (good.getPathType()!=null){
            dto.setPathType(good.getPathType());
        }
        if (good.getAppId()!=null){
            dto.setAppId(good.getAppId());
        }
        result.setMessage("参与成功");
        result.setState(0);
        log.info("isReceive:{}", isReceive);
        if(isReceive !=null && type !=null) {
            if (isReceive == 1 && type == 1) {
                TempSubScribeVm tsm = new TempSubScribeVm();
                tsm.setOpenId(openId);
                tsm.setActivityId(activityId);
                tsm.setPrizeId(prize1.getId());
                tsm.setGoodId(goodId);
                tsm.setGoodName(good.getGoodName());
                tsm.setFlag(1);
                tmpMsgRecordService.sendTemplateMsg(tsm);
            }
        }
//        if (type == 1) {
//                TempSubScribeVm tsm = new TempSubScribeVm();
//                tsm.setOpenId(openId);
//                tsm.setActivityId(activityId);
//                tsm.setGoodId(goodId);
//                tsm.setGoodName(good.getGoodName());
//                tmpMsgRecordService.sendTemplateMsg(tsm);
//        }
        result.setData(dto);
        return result;
    }

    public void verifyPackWxMessageData(PrizeGood good){

    }


    public void addPoint(String memberShipId, Integer addPoint, Integer prizeId,String unionId) {
        String accessToken = accessTokenImpl.getAccessToken();
        String requestUrl = Constants.PointIncr.replace("MEMBERSHIP", memberShipId).replace("ACCESSTOKEN", accessToken);
        PointDTO dto = new PointDTO();
        Date currentTime = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(currentTime);
        calendar.add(Calendar.HOUR, -8);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        String timeStamp = formatter.format(calendar.getTime());
        dto.setContentName("抽中积分");
        dto.setSource("帝亚吉欧会员俱乐部");
        dto.setDate(timeStamp);
        dto.setPattern(4);
        dto.setPoint(addPoint);
        OkHttpClient client = new OkHttpClient().newBuilder()
            .build();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(dto));
        Request request = new Request.Builder()
            .url(requestUrl)
            .method("POST", body)
            .addHeader("Content-Type", "application/json")
            .build();
        try {
            Response response = client.newCall(request).execute();
            String result = new String(response.body().bytes());
            log.info("调用加分接口,返回值:{}", result);
            Prize prize = prizeRepository.findOne(prizeId);
            prize.setAddPoint(true);
            Prize prize1 = prizeRepository.saveAndFlush(prize);
            log.info("加分操作完,prize1:{}", prize1.getAddPoint());
            response.body().close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public Boolean cutStock(Integer goodId, String activityId) {
        Boolean flag = prizeGoodService.cutStock(goodId, activityId);
        return flag;
    }

    public Page<PrizeDTO> prizeList(PrizeListVM vm) {
        //原jpa查询
        /*PageRequest pageRequest = new PageRequest(vm.getPage(), vm.getPageSize(), Sort.Direction.DESC, "createTime");
        Page<Prize> page = prizeRepository.findAll(new Specification() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) {
                List<Predicate> list = new LinkedList<>();
                if (vm.getGoodId() != null) {
                    Predicate goodId = cb.equal(root.get("goodId"), vm.getGoodId());
                    list.add(goodId);
                }
                if (StringUtils.isNotEmpty(vm.getKeyword())) {
                    List<String> unionId = memberRepository.findAllUnionIdByNickNameLike(vm.getKeyword());
                    Predicate keyword = cb.equal(root.get("unionId"), unionId);
                    list.add(keyword);
                }
                if (StringUtils.isNotEmpty(vm.getActivityId())) {
                    Predicate activityId = cb.equal(root.get("activityId"), vm.getActivityId());
                    list.add(activityId);
                }
                Predicate[] pre = new Predicate[list.size()];
                return query.where(list.toArray(pre)).getRestriction();
            }
        }, pageRequest);*/


        //多表多条件分页查询
        StringBuffer sb = new StringBuffer(" from prize p left join prize_ext pe on p.id = pe.prize_id where 1=1");
        if (vm.getGoodId() != null) {
           sb.append(" and p.good_id =").append(vm.getGoodId());
        }
        if (StringUtils.isNotEmpty(vm.getKeyword())) {
            List<String> unionIdList = memberRepository.findAllUnionIdByNickNameLike(vm.getKeyword());
            if(unionIdList != null && !unionIdList.isEmpty()){
                sb.append(" and p.union_id in( ");
                for (String unionId : unionIdList) {
                    sb.append("'").append(unionId).append("',");
                }
                sb.replace(sb.length() - 1, sb.length(), "");
                sb.append(" ) ");
            } else {
                Pageable pageable = new PageRequest(vm.getPage(), vm.getPageSize(),null);
                List<PrizeDTO> newList = new ArrayList<>();
                Page page1 = new PageImpl(newList, pageable, 0);
                return page1;
            }
        }
        if (StringUtils.isNotEmpty(vm.getActivityId())) {
            sb.append(" and p.activity_id ='").append(vm.getActivityId()).append("'");
        }
        if (StringUtils.isNotEmpty(vm.getMobile())) {
            sb.append(" and pe.mobile ='").append(vm.getMobile()).append("'");
        }
        if (StringUtils.isNotEmpty(vm.getCreateTimeStart())) {
            sb.append(" and p.create_time >=DATE_FORMAT('").append(vm.getCreateTimeStart()).append("','%Y-%m-%d %H:%i:%s')");
        }
        if (StringUtils.isNotEmpty(vm.getCreateTimeEnd())) {
            sb.append(" and p.create_time <=DATE_FORMAT('").append(vm.getCreateTimeEnd()).append("','%Y-%m-%d %H:%i:%s')");
        }
        //Sort sort = new Sort(Sort.Direction.DESC,"p.create_time"); //创建时间降序排序
        sb.append(" order by p.create_time desc");
        Pageable pageable = new PageRequest(vm.getPage(), vm.getPageSize(),null);

        Page<Prize> page = this.findByPage(sb.toString(), vm, pageable);

        Page<PrizeDTO> dtoPage = page.map(i -> {
            PrizeDTO dto = prizeMapper.toDto(i);
            List<PrizeExt> ext = prizeExtRepository.findByPrizeId(dto.getId());
            if (ext != null && ext.size() >0) {
                dto.setPrizeExt(ext.get(ext.size()-1));

                // 20210422 导出新加地址字段 格式:姓名+联系电话+收货地址
                String address = "";
                if (StringUtils.isNotBlank(ext.get(ext.size() - 1).getName())){
//                    address = ext.get(ext.size() - 1).getName();
                    dto.setName(ext.get(ext.size() - 1).getName());
                }
                if (StringUtils.isNotBlank(ext.get(ext.size() - 1).getMobile())){
//                    address = address + ext.get(ext.size() - 1).getMobile();
                    dto.setMobile(ext.get(ext.size() - 1).getMobile());
                }
                if (StringUtils.isNotBlank(ext.get(ext.size() - 1).getAddress())){
                    address =  ext.get(ext.size() - 1).getAddress();
                }
                dto.setAddress(address);
            }
            if(dto.getGoodId()!=null){
                dto.setGoodName(prizeGoodService.getName(dto.getGoodId()));
            }
            if(StringUtils.isNotEmpty(dto.getActivityId())){
                dto.setActivityName(prizeGoodService.getActivityName(dto.getActivityId()));
            }
            Member member = memberService.findByUnionId(i.getUnionId());
            if (member != null) {
                dto.setNickName(member.getNickName());
            }
            return dto;
        });
        return dtoPage;
    }


    public Integer count(String unionId) {
        Integer count = prizeRepository.findIsPrize(unionId);
        return count;
    }

    public Integer findGoodIdByPrizeId(Integer prizeId) {
        Integer goodId = prizeRepository.findGoodIdByPrizeId(prizeId);
        return goodId;
    }

    public void createExt(PrizeExtVM vm) {
        PrizeExt ext = new PrizeExt();
        ext.setAddress(vm.getAddress());
        ext.setMobile(vm.getMobile());
        ext.setPrizeId(vm.getPrizeId());
        ext.setName(vm.getName());
        ext.setCreateTime(new Date());
        ext.setUpdateTime(new Date());
        prizeExtRepository.saveAndFlush(ext);
    }

    /**
     * 扣减积分
     *
     * @param memberShipId
     * @return
     */
    public Boolean cutPoint(String memberShipId, Integer cutPoint) {
        Boolean flag = false;
        String accessToken = accessTokenImpl.getAccessToken();
        String requestUrl = Constants.PointDecr.replace("MEMBERSHIP", memberShipId).replace("ACCESSTOKEN", accessToken);
        Date currentTime = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(currentTime);
        calendar.add(Calendar.HOUR, -8);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        String timeStamp = formatter.format(calendar.getTime());
        PointDTO pointDTO = new PointDTO();
        pointDTO.setPoint(cutPoint);
        pointDTO.setPattern(1);
        pointDTO.setDate(timeStamp);
        pointDTO.setSource("帝亚吉欧会员俱乐部");
        pointDTO.setContentName("积分抽奖");
        log.info("dto:{}", pointDTO.toString());
        OkHttpClient client = new OkHttpClient().newBuilder()
            .build();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(pointDTO));
        Request request = new Request.Builder()
            .url(requestUrl)
            .method("POST", body)
            .addHeader("Content-Type", "application/json")
            .build();
        try {
            Response response = client.newCall(request).execute();
            String result = new String(response.body().bytes());
            log.info("调用减分接口,返回值:{}", result);
            if (result.contains("400000")) {
                flag = true;
            }
            response.body().close();
            return flag;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return flag;
    }

    public Prize findByUnionId(String unionId) {
        Prize prize = prizeRepository.findByUnionId(unionId);
        return prize;
    }

    public List<Prize> findByUnionIdAndActivityId(String unionId, String activityId) {
        List<Prize> prizes = prizeRepository.findByUnionIdAndActivityId(unionId, activityId);
        return prizes;
    }

    public PrizeRate editRate(Integer goodId, Integer num) {
        return prizeRateService.editRate(goodId, num);
    }

    public Page<PrizeRate> rateList(Integer page, Integer size) {
        return prizeRateService.getList(page, size);
    }

    public void deleteRate(Integer id) {
        prizeRateService.delete(id);
    }

    public Page<PrizeDTO> findPrizeByUnionId(PrizePageVM vm) {
        PageRequest pageRequest = new PageRequest(vm.getPage(), vm.getPageSize(), Sort.Direction.DESC, "createTime");
        Page<Prize> page = prizeRepository.findAll(new Specification() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) {
                List<Predicate> list = new LinkedList<>();
                Predicate goodId = cb.equal(root.get("unionId"), vm.getUnionId());
                list.add(goodId);
                Predicate[] pre = new Predicate[list.size()];
                return query.where(list.toArray(pre)).getRestriction();
            }
        }, pageRequest);
        Page<PrizeDTO> dtoPage = page.map(i -> {
            PrizeDTO dto = prizeMapper.toDto(i);
            List<PrizeExt> ext = prizeExtRepository.findByPrizeId(dto.getId());
            if (ext != null && ext.size() >0) {
                dto.setPrizeExt(ext.get(ext.size()-1));
            }
            if(dto.getGoodId()!=null){
                PrizeGood good = prizeGoodService.findById(dto.getGoodId());
                if(good !=null){
                    dto.setGoodName(good.getGoodName());
                    dto.setGoodImg(good.getGoodImg());
                    dto.setType(good.getType());
                    dto.setPoint(good.getPoint());
                    dto.setCardId(good.getCardId());
                    dto.setGoodImg(good.getGoodImg());
                    dto.setPoint(good.getPoint());
                    dto.setPathType(good.getPathType());
                    dto.setButtonText(good.getButtonText());
                    dto.setRemark(good.getRemark());
                    dto.setAppId(good.getAppId());
                    dto.setPagePath(good.getPagePath());
                    dto.setCouponType(good.getCouponType());
                    dto.setMgmUrl(good.getMgmUrl());
                    dto.setMgmButtonName(good.getMgmButtonName());
                    dto.setMgmStatus(good.getMgmStatus());
                    dto.setQrCodeId(good.getQrCodeId());
                    dto.setHxContent1(good.getHxContent1());
                    dto.setHxContent2(good.getHxContent2());
//                    if(good.getType() ==4) {
//                       // List<PrizeCode> code = uploadCodeService.findByGoodIdAndUnionId(dto.getGoodId(), vm.getUnionId());
//                        PrizeCode code = uploadCodeService.findPrizeCodeByGoodIdAndUnionId(dto.getGoodId(), vm.getUnionId());
//                        if (code != null) {
//                            dto.setCouponCode(code.getCode());
//                        }
//                    }
                    // 查询订单号
                    List<OrderRecord> orders = orderService.getOrderOneByCarRollPrizeId(vm.getUnionId(), good.getId().toString(),dto.getId());
                    orders.stream().findFirst().ifPresent(order ->
                        {
                            dto.setOrderCode(order.getOrderCode());
                            dto.setAddress(order.getAddress());
                            dto.setMobile(order.getMobile());
                            dto.setName(order.getName());
                        }
                    );
                }
            }
            Member member = memberService.findByUnionId(i.getUnionId());
            if (member != null) {
                dto.setName(member.getNickName());
            }
            DrawActivity activity = drawActivityRepository.findOne(dto.getActivityId());
            if (activity != null) {
                dto.setActivityType(activity.getActivityType());
            }
            return dto;
        });
        return dtoPage;
    }

    public JsonResult prizeLLs(String unionId, List<PrizeGood> pglist, String memberShipId, String activityId, Integer cutPoint, NewPrizeVM vm) {
        JsonResult result = new JsonResult();
        Prize prize = null;
        Integer goodId = null;
        lock.lock();
        try {
            List<PrizeGood> enableGoods = prizeGoodService.getEnableIdsAndStockIsNotNullByActivityId(activityId);
            if (pglist != null && pglist.size()>0){
                HashSet list1 = new HashSet(enableGoods);
                HashSet list2 = new HashSet(pglist);
                list1.removeAll(list2);
                enableGoods.removeAll(pglist);
                enableGoods.clear();
                enableGoods.addAll(list1);
            }
            if (enableGoods.size() == 0) {
                result.setState(-1);
                result.setMessage("很遗憾您未抽中，谢谢参与");
                return result;
            }
            Double maxNum = 0d;
            for (PrizeGood good : enableGoods) {
                maxNum = maxNum + good.getProbability();
            }
            if (maxNum == 0) {
                result.setState(-1);
                result.setMessage("概率出问题了");
                return result;
            }
            log.info("最大数:{}", maxNum);
            //获取0-总概率值得随机数
            double min = 0d;
            Double randomNum = min + new Random().nextDouble() * (maxNum - min);
            log.info("randomNum:{}", randomNum);
            for (PrizeGood good : enableGoods) {
                randomNum = randomNum - good.getProbability();
                if (randomNum <= 0) {
                    goodId = good.getId();
                    break;
                }
            }
            codeUserService.codeEdit(vm);
            log.info("奖品id:{}", goodId);
            Boolean flag = cutStock(goodId, activityId);
            if (!flag) {
                result.setState(-1);
                result.setMessage("系统繁忙");
                return result;
            }
        } catch (Exception e) {
            log.error("e:{}", e);
        } finally {
            lock.unlock();
        }
        //扣分
        cutPoint(memberShipId, cutPoint);
        log.info("扣分结束");
        prize = new Prize();
        prize.setUnionId(unionId);
        //奖品ID
        prize.setGoodId(goodId);
        prize.setCreateTime(new Date());
        prize.setUpdateTime(new Date());
        prize.setAddPoint(false);
        if (StringUtils.isNotEmpty(activityId)) {
            prize.setActivityId(activityId);
        }
        Prize prize1 = prizeRepository.saveAndFlush(prize);
        //通过奖品ID获取当前时间的奖品
        PrizeGood good = prizeGoodService.findById(goodId);
        PrizeDTO dto = prizeMapper.toDto(prize);
        if(good.getType() ==4){
            log.info("抽中卡券:{}",good.getId());
            PrizeCode code =uploadCodeService.findRandomCodeNoUse(good.getId());
            dto.setCouponCode(code.getCode());
            code.setIsUse(2);
            code.setUnionId(unionId);
            code.setUseDate(new Date());
            code.setPrizeId(prize1.getId());
            uploadCodeService.edit(code);
        }
        if (StringUtils.isNotEmpty(good.getGoodName())) {
            dto.setGoodName(good.getGoodName());
        }
        dto.setType(good.getType());
        //增加奖品图片
        if (StringUtils.isNotEmpty(good.getGoodImg())) {
            dto.setGoodImg(good.getGoodImg());
        }
        if (StringUtils.isNotEmpty(good.getPagePath())) {
            dto.setPagePath(good.getPagePath());
        }
        if (null != good.getPoint()) {
            dto.setPoint(good.getPoint());
        }
        if (StringUtils.isNotEmpty(good.getCardId())) {
            dto.setCardId(good.getCardId());
        }
        if (StringUtils.isNotEmpty(good.getCode())) {
            dto.setCode(good.getCode());
        }
        if (StringUtils.isNotEmpty(good.getCouponType())) {
            dto.setCouponType(good.getCouponType());
        }
        log.info("dto:{}", dto.toString());
        if (good.getType() == 0) {
            if (good.getPoint() == null || good.getPoint() == 0) {
                good.setPoint(50);
            }
        }
        final Integer prizeId = prize.getId();
        if (good.getType() == 0) {
            ExecutorService service = Executors.newSingleThreadExecutor();
            service.execute(() -> {
                addPoint(memberShipId, good.getPoint(), prizeId,unionId);
                log.info("加分结束");
            });
        }

        dto.setButtonText(good.getButtonText());

        if (good.getRemark()!=null){
            dto.setRemark(good.getRemark());
        }

        if (good.getPathType()!=null){
            dto.setPathType(good.getPathType());
        }
        if (good.getAppId()!=null){
            dto.setAppId(good.getAppId());
        }
        result.setMessage("参与成功");
        log.info("isReceive:{}", vm.getIsReceive());
        log.info("dto:{}", vm.getType());
        if(vm.getIsReceive()!=null && vm.getType() !=null){
            if(vm.getIsReceive() ==1 && vm.getType() == 1){
                TempSubScribeVm tsm =new TempSubScribeVm();
                tsm.setOpenId(vm.getOpenId());
                tsm.setActivityId(activityId);
                tsm.setGoodId(goodId);
                tsm.setGoodName(good.getGoodName());
                tmpMsgRecordService.sendTemplateMsg(tsm);
            }
        }
//        if(vm.getType() == 1){
//            TempSubScribeVm tsm =new TempSubScribeVm();
//            tsm.setOpenId(vm.getOpenId());
//            tsm.setActivityId(activityId);
//            tsm.setGoodId(goodId);
//            tsm.setGoodName(good.getGoodName());
//            tmpMsgRecordService.sendTemplateMsg(tsm);
//        }
        result.setState(0);
        result.setData(dto);
        return result;
    }
    public List<Prize> findUnionId(String unionId){
        return prizeRepository.findUnionId(unionId);
    }

    public List<Prize> findByUnionIdAndGoodId(String unionId, Integer goodId) {
        List<Prize> byUnionIdAndGoodId = prizeRepository.findByUnionIdAndGoodId(unionId, goodId);
        return byUnionIdAndGoodId;
    }

    public Prize findByUnionIdAndActivityIdAndGoodId(String unionId, String activityId, Integer goodId) {
        Prize prize = prizeRepository.findByUnionIdAndActivityIdAndGoodId(unionId, activityId,goodId);
        return prize;
    }

//    public Page<PrizeCodeDTO> findCodePrizeByUnionId(PrizePageVM vm) {
//        PageRequest pageRequest = new PageRequest(vm.getPage(), vm.getPageSize(), Sort.Direction.DESC, "createTime");
//        Page<PrizeCode> page = prizeCodeRepository.findAll(new Specification() {
//            @Override
//            public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) {
//                List<Predicate> list = new LinkedList<>();
//                Predicate goodId = cb.equal(root.get("unionId"), vm.getUnionId());
//                Predicate goodId1 = cb.equal(root.get("activityId"), vm.getActivityId());
//                list.add(goodId);
//                list.add(goodId1);
//                Predicate[] pre = new Predicate[list.size()];
//                return query.where(list.toArray(pre)).getRestriction();
//            }
//        }, pageRequest);
//        Page<PrizeCodeDTO> dtoPage = page.map(i -> {
//            PrizeCodeDTO dto = toDto(i);
//            if(i.getPrizeGoodId()!=null){
//                PrizeGood good =prizeGoodService.findById(dto.getPrizeGoodId());
//                List<PrizeExt> ext = prizeExtRepository.findByPrizeId(dto.getPrizeGoodId());
//                if (ext != null && ext.size() >0) {
//                    dto.setPrizeExtList(ext.get(ext.size()-1));
//                }
////                PrizeGood good = prizeGoodService.findById(dto.getGoodId());
//                dto.setGoodName(good.getGoodName());
//                dto.setGoodImg(good.getGoodImg());
//                dto.setType(good.getType());
//                dto.setPoint(good.getPoint());
//                dto.setCardId(good.getCardId());
//                dto.setGoodImg(good.getGoodImg());
//                dto.setPoint(good.getPoint());
//                dto.setPathType(good.getPathType());
//                dto.setButtonText(good.getButtonText());
//                dto.setRemark(good.getRemark());
//                dto.setAppId(good.getAppId());
//                dto.setPagePath(good.getPagePath());
////                if(good.getType() ==4) {
////                    PrizeCode code = uploadCodeService.findPrizeCodeByGoodIdAndUnionId(dto.getPrizeGoodId(), vm.getUnionId());
////                    if (code != null) {
////                        dto.setCouponCode(code.getCode());
////                    }
////                }
//            }
//            Member member = memberService.findByUnionId(i.getUnionId());
//            if (member != null) {
//                dto.setName(member.getNickName());
//            }
//            return dto;
//        });
//        return dtoPage;
//    }


    public PrizeCode findPrizeCode(CodeVM vm) {
        return  prizeCodeRepository.findByPrizeId(vm.getPrizeId());
    }


    public CouponReturnVm getCouponReturnVm(DwaIsReceiveVM vm) {
        List<DwaGetCoupon> list = dwaGetCouponService.findByActivityIdAndUnionId(vm.getActivityId(),vm.getUnionId());
        DwaConvertCode codeEntity = dwaGetCouponService.findTopCouponByUnionId(vm.getUnionId());
        CouponReturnVm cpvm = new CouponReturnVm();
        if(codeEntity !=null){
            cpvm.setTopCoupon(codeEntity);
        }
        //根据活动id查询券信息
        if(list!=null && list.size() >0){
            List<Integer> goodIds =new ArrayList<>();
            for (DwaGetCoupon dwa:list) {
                goodIds.add(dwa.getGoodId());
            }
            List<PrizeGood> pglist = prizeGoodService.findDwaByActivityIdAndGoodIds(vm.getActivityId(),goodIds);
            List<PrizeGood> returnList =new ArrayList<>();
            if(pglist !=null && pglist.size() >0){
                for (PrizeGood pg:pglist) {
                    Prize prize =findByUnionIdAndActivityIdAndGoodId(vm.getUnionId(),vm.getActivityId(),pg.getId());
                    if(prize !=null){
                        pg.setId(prize.getId());
                        pg.setGoodId(pg.getId());
                    }
                    returnList.add(pg);
                }
            }
            if(returnList !=null && returnList.size() >0) {
                Map<String, List<PrizeGood>> map = returnList.stream().collect(
                    Collectors.groupingBy(o -> CouponUtils.parse_yyyyMM(o.getStartTime()))
                );
                Map<String, List<PrizeGood>> listMap = CouponUtils.sortByKey(map);
                cpvm.setBottomCoupon(listMap);
            }
        }
        return cpvm;
    }

    //核销
    public HxPrizeDTO hxPrize(PrizeHxVM vm) {
        HxPrizeDTO hxPrizeDTO = new HxPrizeDTO();

        QrCode QrCode = qrCodeRepository.findOne(vm.getBeScanCode());
        if (QrCode == null) {
            hxPrizeDTO.setHxReturn(5);
            return hxPrizeDTO;
        } else {
            PrizeGood prizeGood = prizeGoodService.findById(vm.getGoodId());
            //对比传入的二维码与核销券的二维码id
            if (prizeGood == null || StringUtils.isEmpty(prizeGood.getQrCodeId())
                || !StringUtils.equals(QrCode.getId(), prizeGood.getQrCodeId())) {
                hxPrizeDTO.setHxReturn(6);
                return hxPrizeDTO;
            }
            Prize prize = prizeRepository.findByUnionIdAndId(vm.getUnionId(), vm.getId());
            //List<Prize> listPrize = prizeRepository.findByUnionIdAndGoodId(vm.getUnionId(), vm.getGoodId());
            if (prize != null) {
                if (StringUtils.isNotEmpty(prize.getBeScanCode())) {
                    hxPrizeDTO.setHxReturn(2);
                    return hxPrizeDTO;
                } else {
                    if (prizeRepository.updatePrizeByHx(vm.getBeScanCode(), vm.getUnionId(), vm.getId()) == 1) {

                        QrCodeScan dtoScan = new QrCodeScan();
                        dtoScan.setQrCodeId(QrCode.getId());
                        dtoScan.setSceneName(QrCode.getSceneName());
                        dtoScan.setSceneValue(QrCode.getSceneValue());
                        dtoScan.setUnionId(vm.getUnionId());
                        dtoScan.setGoodId(vm.getGoodId());
                        //dtoScan.setGoodCode(String.valueOf(vm.getGoodId()));
                        dtoScan.setScanTime(new Date());
                        dtoScan.setPrizeId(vm.getId());
                        dtoScan.setAssociatedKeyword(QrCode.getAssociatedKeyword());
                        qrCodeScanRepository.saveAndFlush(dtoScan);
                        //次数加一
                        QrCode dto = qrCodeRepository.findOne(vm.getBeScanCode());
                        int count = dto.getScanningVolume() + 1;
                        dto.setScanningVolume(count);
                        qrCodeRepository.saveAndFlush(dto);
                        hxPrizeDTO.setHxReturn(1);
                        //查询埋点需要的参数
                        DrawActivity activity = drawActivityRepository.findOne(prize.getActivityId());
                        PrizeGood good = prizeGoodService.findById(prize.getGoodId());
                        hxPrizeDTO.setActivityName(activity.getActivityName());
                        hxPrizeDTO.setCampaignID(activity.getCampaignID());
                        hxPrizeDTO.setGoodName(good.getGoodName());
                        hxPrizeDTO.setSceneName(QrCode.getSceneName());
                        hxPrizeDTO.setAssociatedKeyword(QrCode.getAssociatedKeyword());
                        return hxPrizeDTO;
                    } else {
                        hxPrizeDTO.setHxReturn(0);
                        return hxPrizeDTO;
                    }
                }

            } else {

                hxPrizeDTO.setHxReturn(0);
                return hxPrizeDTO;
            }
        }
    }

    /**
     * 更新或新增抽奖次数记录
     * */
    public void saveOrUpdateDrawPrizeCount (String activityId,String unionId) {
        DrawPrizeCount drawPrizeCount = drawPrizeCountRepository.queryDrawPrizeCountByActivityId(activityId,unionId);
        if (drawPrizeCount != null) {
            drawPrizeCount.setPrizeNum(drawPrizeCount.getPrizeNum() + 1);
            drawPrizeCount.setUpdateTime(new Date());
            drawPrizeCountRepository.saveAndFlush(drawPrizeCount);
        } else {
            DrawPrizeCount newDrawPrizeCount = new DrawPrizeCount();
            newDrawPrizeCount.setUnionId(unionId);
            newDrawPrizeCount.setActivityId(activityId);
            newDrawPrizeCount.setPrizeNum(1);
            newDrawPrizeCount.setUpdateTime(new Date());
            drawPrizeCountRepository.saveAndFlush(newDrawPrizeCount);
        }
    }

    public JsonResult queryHxLaunchHelp (LaunchHelpVM vm) {
        JsonResult result = new JsonResult();
        result.setState(0);
        result.setMessage("查询成功");
        LaunchHelpDTO dto = new LaunchHelpDTO();
        //默认0显示发起助力
        Integer launchHelpStatus = 0;
        //默认核销状态 0未核销
        Integer hxStatus = 0;
        Prize prize = prizeRepository.findOne(vm.getPrizeId());
        //BeScanCode为空 未核验
        if (prize != null) {
            if (StringUtils.isNotEmpty(prize.getBeScanCode())) {
                //BeScanCode非空 已核验
                hxStatus = 1;
                //查询二维码场景以及扫码时间
                QrCode qrCode = qrCodeRepository.findOne(prize.getBeScanCode());
                if (qrCode != null) {
                    List<QrCodeScan> qrCodeScanList = qrCodeScanRepository.findAll(new Specification() {
                        @Override
                        public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) {
                            List<Predicate> list = new LinkedList<>();
                            Predicate unionId = cb.equal(root.get("unionId"), vm.getUnionId());
                            Predicate goodId = cb.equal(root.get("goodId"), vm.getGoodId());
                            Predicate qrCodeId = cb.equal(root.get("qrCodeId"), qrCode.getId());
                            Predicate prizeId = cb.equal(root.get("prizeId"), vm.getPrizeId());
                            list.add(unionId);
                            list.add(goodId);
                            list.add(qrCodeId);
                            list.add(prizeId);
                            Predicate[] pre = new Predicate[list.size()];
                            return query.where(list.toArray(pre)).getRestriction();
                        }
                    });
                    if (!CollectionUtils.isEmpty(qrCodeScanList)) {
                        QrCodeScan qrCodeScan = qrCodeScanList.get(0);
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        dto.setSceneName(qrCodeScan.getSceneName());
                        dto.setScanTime(qrCodeScan.getScanTime());
                    }

                } else {
                    log.info("查询二维码信息res为空：BeScanCode " + prize.getBeScanCode());
                }
            }
            dto.setHxStatus(hxStatus);
        } else {
            log.info("查询prize res为空：prizeId " + vm.getPrizeId());
            result.setState(-1);
            result.setMessage("系统异常");
            return result;
        }

        MdmHelpActivity activity = mdmHelpActivityRepository.findOne(vm.getMdmHelpActivityId());
        if(activity ==null){
            log.info("不存在此活动!，不显示发起助力");
            launchHelpStatus = 1;
        }
        //校验活动是否开启
        if(activity.getIsOpen() ==2){
            log.info("该活动暂未开启!，不显示发起助力");
            launchHelpStatus = 1;
        }
        //校验活动是否开启
        long currentTime = ZonedDateTime.now().toInstant().getEpochSecond() / 60;
        long startTime = activity.getStartTime().toInstant().getEpochSecond() / 60;
        long endTime = activity.getEndTime().toInstant().getEpochSecond() / 60;
        if(currentTime < startTime || currentTime >endTime){
            log.info("不在活动有效时间内!，不显示发起助力");
            launchHelpStatus = 1;
        }
        List<MdmHelpMsg> list = mdmHelpMsgRepository.findByMdmHelpActivityIdAndCreateUnionId(vm.getMdmHelpActivityId(), vm.getUnionId());
        log.info("当前助力总数--" +list.size());
        log.info("活动设置总助力人数--" +activity.getHelpPeopleCount());
        if(list !=null && list.size() >0){
            if(activity !=null){
                if(activity.getHelpPeopleCount() <= list.size()){
                    log.info("助力活动已完成，不显示发起助力");
                    launchHelpStatus = 1;
                }
            }
        }

        //返回是否显示助力
        dto.setLaunchHelpStatus(launchHelpStatus);
        result.setData(dto);
        return result;
    }

    /**
     * 多表多条件分页
     * */
    public Page<Prize> findByPage(String sb, PrizeListVM vm, Pageable pageable) {
        StringBuffer before = new StringBuffer("select *");
        StringBuffer count = new StringBuffer("select count(*)");
        before.append(sb);
        count.append(sb);
        //通过组装好的sql创建查询引擎对象Query
        Query query =   entityManager.createNativeQuery(before.toString(),Prize.class);

        //需要分页时，可在此处添加
        query.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
        query.setMaxResults(pageable.getPageSize());
        List<Prize> objectList = query.getResultList();  //获取查询结果

        //查询条数
        Query countTotal =   entityManager.createNativeQuery(count.toString());
        //int singleResult = (int)countTotal.getSingleResult();
        BigInteger singleResult1 = (BigInteger) countTotal.getSingleResult();
        int totalCount = singleResult1.intValue();
        if (CollectionUtils.isEmpty(objectList)) {
            List<Prize> newList = new ArrayList<>();
            Page page1 = new PageImpl(newList, pageable, totalCount);
            return page1;
        } else {
            Page page1 = new PageImpl(objectList, pageable, totalCount);
            return page1;
        }

    }

}
